package com.myproject.mall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myproject.mall.common.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public final class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON serialization failed", e);
        }
    }
    
    public static <T> T toObject(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON反序列化失败", e);
        }
    }

    public static <T> T toObject(Map<String, String> map, TypeReference<T> type) {
        try {
            if(map == null || map.isEmpty()) return null;
            Map<String, Object> stringKeyMap = new HashMap<>();
            for(Map.Entry<String, String> entry : map.entrySet()) {
                String value = entry.getKey();
                String json = entry.getValue();

                Object parsed = parseJsonValue(json);
                stringKeyMap.put(entry.getKey(), parsed);
            }
            return mapper.convertValue(stringKeyMap, type);
        } catch (Exception e) {
            log.error("JSON反序列化失败", e);
            throw new GlobalException("JSON反序列化失败:".concat(e.getMessage()));
        }
    }

    private static Object parseJsonValue(String json) {
        try {
            return mapper.readValue(json, Object.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON反序列化失败", e);
        }
    }
}
